<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        die();
    }

    public function update_applier(){
        Db::query("UPDATE qa_outsideschool SET applier_id='202302175',applier_name = '林 雪 菲' WHERE applier_id ='15610001073'");
    }


    // 获取校外人员预约，教师名称为空的
    public function outside(){
        $list = Db::name('outsideschool')->where('applier_id<>0')->where('applier_name','')->where('id>76780')->order('id asc')->select();
        foreach($list as $key => $val) {
            
            if(!empty($val['applier_id'])){
                $applier_name = Db::name('teacher')->where('tel',$val['applier_id'])->where('type',1)->value('nickname');
                if(isset($applier_name)){
                    Db::name('outsideschool')->where('id',$val['id'])->update(['applier_name'=>$applier_name,'is_outside'=>1]);
                }
            }

            if(!empty($val['check_sid'])){
                $applier_name1 = Db::name('teacher')->where('tel',$val['check_sid'])->where('type',1)->value('nickname');
                if(isset($applier_name1)){
                    Db::name('outsideschool')->where('id',$val['id'])->update(['check_cn'=>$applier_name1,'is_outside'=>2]);
                }
            }

        }
    }

    public function outside1(){
        $list = Db::name('outsideschool')->where('is_check<>0')->where('check_cn is null')->order('id asc')->select();
        unset($val);
        foreach($list as $key => $val) {
            if(!empty($val['check_sid'])){
                $applier_name1 = Db::name('teacher')->where('tel',$val['check_sid'])->where('type',1)->value('nickname');
                if(isset($applier_name1)){
                    Db::name('outsideschool')->where('id',$val['id'])->update(['check_cn'=>$applier_name1,'is_outside'=>2]);
                }
            }
        }
    }


    public function teacher(){
        $list = Db::name('outsideschool')->where('is_schoolfriend=0 and reception_id<>59 and applier_id>0')->field('applier_name,applier_id')->order('id asc')->select();
        unset($val);
        foreach($list as $key => $val) {
            if(!empty($val['applier_id'])){
                $teacher = Db::name('teacher')->where('tel',$val['applier_id'])->where('type',1)->find();
                if(empty($teacher)){
                    $insert = [
                        'nickname'=>$val['applier_name'],
                        'tel'=>$val['applier_id'],
                        'type'=>1,
                        'inwhitelist'=>1,
                        'create_time'=>time(),
                    ];
                   Db::name('teacher')->insert($insert);
                }
            }
        }
        exit('完成');
    }

    public function applierid(){
        $list = Db::name('outsideschool')->where('applier_id is null ')->order('id asc')->select();
        unset($value);
        foreach($list as $key => $value) {
            if(!empty($value['tel'])){
                $dbconn=oci_connect('user_xyb_xy','QauXybXy12#$',"(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.8.16.80)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=icdc)))","UTF8");
                if (!$dbconn) {
                   echo '连接失败';
                   die();
                }
                $sql="select * from icdc_ods.view_xyb_xy_wlryrxxx where SJHM='".$value['tel']."'";
                $data = $this -> exec($dbconn,$sql);
                if(!empty($data)){
                   Db::name('outsideschool')->where('id',$value['id'])->update(['applier_id'=>$data[0]['APPLIER_ID']]);     
                }
            }
        }
        halt(count($list));
    }

    protected function exec($dbconn = null, $sql = ''){
        $stid = oci_parse($dbconn, $sql); // 配置SQL语句，准备执行
        if (!$stid) {
            $e = oci_error($dbconn);
            print htmlentities($e['message']);
            exit;
        }
        $r = oci_execute($stid, OCI_DEFAULT); // 执行SQL。OCI_DEFAULT表示不要自动commit
        if(!$r) {
            $e = oci_error($stid);
            echo htmlentities($e['message']);
            exit;
        }


        oci_fetch_all($stid,$data);

        $insertData = [];
        foreach ($data as $k => $v){
            foreach ($v as $kk => $vv){
                $insertData[$kk][$k] = $vv;
            }
        }
        return $insertData;
    }

    // public function send(){
    //     $arr = [18661473759];
    //     foreach ($arr as $key => $value) {
    //         $sm='【青岛农业大学】亲爱的测试人员,这是一条测试短信。';
    //         $res = $this->sendtelsms($sm,$value);
    //         // $res = json_decode($res,true);
    //         // echo $res['success']."####".$res['id'];
    //         // exit();
    //     }
    // }

    public function sendtelsms($sm = null,$tel = null){
        $sm = urlencode($sm);
        $sm_url = 'http://api.qirui.com:7891/mt?dc=8&un=1267770012&pw=67d0eddeaf4c9ad2dcd0&sm='.$sm.'&da='.$tel.'&tf=3&rf=2&rd=0';
        $data=  file_get_contents($sm_url);
        return $data;
    }


    public function outsideschool(){
        $st = Db::name('outsideschool')->where("is_schoolfriend=1 and is_check=1 and is_use=0 and admission_starttime>=20230524")->order('id asc')->select();
        foreach($st as $k => $v) {
            $info = Db::name('sendsms')->where('is_send=1')->where('outsideschool_id',$v['id'])->find();
            if(empty($info)){
                $fo = Db::name('phone')->where('tel',$v['tel'])->find();
                if(empty($fo)){
                    $tel[] = ['id'=>$v['id'],'nickname'=>$v['nickname'],'tel'=>$v['tel']];
                }
            }
        }
        
        unset($value);
        foreach ($tel as $key => $value)
        {
            $outsideschool_info = Db::name('outsideschool')->where(['id' => $value['id']])->find();
            $sms_arr = array();
            $sms_arr['nickname'] = $outsideschool_info['nickname'];
            $sms_arr['is_check'] = $outsideschool_info['is_check'];
            $sms_arr['check_cn'] = $outsideschool_info['check_cn'];
            $sms_arr['outsideschool_id'] = $value['id'];
            if ($outsideschool_info['is_check'] == 1){
                $sm='【青岛农业大学】亲爱的'.$outsideschool_info['nickname'].'校友,您的入校申请已审核,欢迎您回母校! 入校时间:'.$outsideschool_info['admission_starttime'].'。如已收到过短信,请忽略此消息';
                if(empty($outsideschool_info['zy'])){
                    $sm='【青岛农业大学】亲爱的'.$outsideschool_info['nickname'].'(校友随行人),您的入校申请已审核,欢迎您们回母校!入校时间:'.$outsideschool_info['admission_starttime'].'。如已收到过短信,请忽略此消息';
                }
                $send_res = $this->sendtelsms($sm,$outsideschool_info['tel']);
                $send_sult = json_decode($send_res,true);
                if(isset($send_sult['success']) && isset($send_sult['id'])){
                    $sms_arr['is_send'] = 1;
                    $sms_arr['send_json'] = $send_res;
                }else{
                    $sms_arr['is_send'] = 0;
                    $sms_arr['send_json'] = $send_res;
                }
                $sms_arr['is_schoolfriend'] = 1;
                $sms_arr['sm'] = $sm;
                $sms_arr['tel'] = $outsideschool_info['tel'];
                $sms_arr['admission_starttime'] = $outsideschool_info['admission_starttime'];
                $sms_arr['create_time'] = time();
                Db::name('sendsms')->insert($sms_arr);
            } 
        }
        print_r($tel);
        exit('完成');
    }

    /**
     * 我们自己的加密
     * @param $str 待加密的字段
     * @return string
     */
    public function encrypt($string)
    {
        //公钥内容 一行的形式
        $pubKey= '044dfcc4b51f91e632b7c04e9b825691758a44d6cd0a8bf22041750f3dc0a09a4c25f788384c74d5fbf4e25703cc2e92366e82dc8e6cd0316ec72f98fe3ab30696';//'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgqM3anzJDv0c/bD3tT3oOllQBopHtdxTaoLXUiq3pABcO3cFSF6wlGPNgvqI1K1QrMLTQI6Sz/YfN9FehgGMC4W/KmwyFA1im97lx8OWtkV2vc7meXqO0rntW6CX3wULeXxvwWeWgfIn+gRpZ/dlrnFTajTAe0OvIuTu8w7UNbpcQvFV0gKmB7YqjJER/pK5wdDfCkB2stEqRrZ0zCmJ+yfpJGqp9EPsYsL8JEe9PXL1z80w7ILu+Bqja5NfxCX0Vsdf+1YhzqkaFpSxvKUXu+EZXV6G6J6339H2R4f/uuF5jxonJPAxqFXV8tFQ4fSQmXf7G9XbHO2bqXLgFqNoaQIDAQAB';
     
        $res = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($pubKey, 64, "\n", true) .
            "\n-----END PUBLIC KEY-----";
     
        openssl_public_encrypt($string, $encrypt, $res);
     
        return base64_encode($encrypt);
    }

    /**
     * 我们自己的解密
     * @param $secret 加密后的base64字段
     * @return string
     */
    public function decrypt($secret)
    {
        //私钥内容 一行的形式
        $privateKey = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCCozdqfMkO/Rz9sPe1Peg6WVAGike13FNqgtdSKrekAFw7dwVIXrCUY82C+ojUrVCswtNAjpLP9h830V6GAYwLhb8qbDIUDWKb3uXHw5a2RXa9zuZ5eo7Sue1boJffBQt5fG/BZ5aB8if6BGln92WucVNqNMB7Q68i5O7zDtQ1ulxC8VXSAqYHtiqMkRH+krnB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ly7cxrW+UhR5UVrVEz2bkrf6k+bIgpJzu1GoY+OpdpRjIntySuxeT3a0NPafOcQDiTeh2OYl3MbJeeSVfl65B1O4O87gD5Bnr6+4ULmYUwjFJzGmvYg5m1GxYtAoGADGU0fr7BjQCeb6/VfPlgAotlrCp0hcfhCgSaaOc3D6qXdt6xqlK0CoKFDoW3Nd1krz6JDz9V0m2b30oBwjL9yLR5df2OpJG19KPIaI8EqqJ6onu48dZ9Mo7epE5D90LICbyJ9iChnCOadb0moU1f6O1J3CZapjEuWUDay2zOP1s=';
        $public_pem='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgqM3anzJDv0c/bD3tT3oOllQBopHtdxTaoLXUiq3pABcO3cFSF6wlGPNgvqI1K1QrMLTQI6Sz/YfN9FehgGMC4W/KmwyFA1im97lx8OWtkV2vc7meXqO0rntW6CX3wULeXxvwWeWgfIn+gRpZ/dlrnFTajTAe0OvIuTu8w7UNbpcQvFV0gKmB7YqjJER/pK5wdDfCkB2stEqRrZ0zCmJ+yfpJGqp9EPsYsL8JEe9PXL1z80w7ILu+Bqja5NfxCX0Vsdf+1YhzqkaFpSxvKUXu+EZXV6G6J6339H2R4f/uuF5jxonJPAxqFXV8tFQ4fSQmXf7G9XbHO2bqXLgFqNoaQIDAQAB';
     
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($privateKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
     
        openssl_private_decrypt(base64_decode($secret), $oldData, $res);
     
        return $oldData;
    }


    /**
     * 生成签名
     * @param array $params 待签名的所有参数
     * @return string 生成的签名
     */
    public function getSignGenerator($params)
    {
        //生成待验签的字符串
        // $data = $this->getSignStr($params);
        //私钥的内容 一行的格式
        $privateKey = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCCozdqfMkO/Rz9sPe1Peg6WVAGike13FNqgtdSKrekAFw7dwVIXrCUY82C+ojUrVCswtNAjp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P/eqTaAnmGf8dx4pqp5izPqAhtmYwBZo1kN9HQffjMCkjcgW0YCSCOs/9lcSKicVayArJAoGBAIGc9j/NVRrl2DKIoEuNVR884hUJAm7RFh7aiy5CKWF29DLM/Dly7cxrW+UhR5UVrVEz2bkrf6k+bIgpJzu1GoY+OpdpRjIntySuxeT3a0NPafOcQDiTeh2OYl3MbJeeSVfl65B1O4O87gD5Bnr6+4ULmYUwjFJzGmvYg5m1GxYtAoGADGU0fr7BjQCeb6/VfPlgAotlrCp0hcfhCgSaaOc3D6qXdt6xqlK0CoKFDoW3Nd1krz6JDz9V0m2b30oBwjL9yLR5df2OpJG19KPIaI8EqqJ6onu48dZ9Mo7epE5D90LICbyJ9iChnCOadb0moU1f6O1J3CZapjEuWUDay2zOP1s=';
     
        $pem = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($privateKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";
     
        //openssl_private_encrypt($data, $crypted, $pem);
        openssl_sign($params, $sign, $pem, OPENSSL_ALGO_SHA256);
     
        $sign = base64_encode($sign);
     
        return $sign;
    }

    /**
     * 验证签名
     * @param array $params 待签名的所有参数
     * @param string $sign 生成的签名
     * @return boolean 校验的结果
     */
    public function signCheck($params, $sign)
    {
        //生成待验签的字符串
        // $data = $this->getSignStr($params);
        //对方的公钥内容 一行的形式
        $publicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgqM3anzJDv0c/bD3tT3oOllQBopHtdxTaoLXUiq3pABcO3cFSF6wlGPNgvqI1K1QrMLTQI6Sz/YfN9FehgGMC4W/KmwyFA1im97lx8OWtkV2vc7meXqO0rntW6CX3wULeXxvwWeWgfIn+gRpZ/dlrnFTajTAe0OvIuTu8w7UNbpcQvFV0gKmB7YqjJER/pK5wdDfCkB2stEqRrZ0zCmJ+yfpJGqp9EPsYsL8JEe9PXL1z80w7ILu+Bqja5NfxCX0Vsdf+1YhzqkaFpSxvKUXu+EZXV6G6J6339H2R4f/uuF5jxonJPAxqFXV8tFQ4fSQmXf7G9XbHO2bqXLgFqNoaQIDAQAB';
     
        $pem = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($publicKey, 64, "\n", true) .
            "\n-----END PUBLIC KEY-----";
     
        $checkResult = (bool)openssl_verify($params, base64_decode($sign), $pem, OPENSSL_ALGO_SHA256);
     
        return $checkResult;
    }

    /**
     * 
     * [zhifu description]
     * @return [type] [description]
     */
    public function zhifu(){


        $private_pem='MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCCozdqfMkO/Rz9sPe1Peg6WVAGike13FNqgtdSKrekAFw7dwVIXrCUY82C+ojUrVCswtNAjpLP9h830V6GAYwLhb8qbDIUDWKb3uXHw5a2RXa9zuZ5eo7Sue1boJffBQt5fG/BZ5aB8if6BGln92WucVNqNMB7Q68i5O7zDtQ1ulxC8VXSAqYHtiqMkRH+krnB0N8KQHay0SpGtnTMKYn7J+kkaqn0Q+xiwvwkR709cvXPzTDsgu74GqNrk1/EJfRWx1/7ViHOqRoWlLG8pRe74RldXobonrff0fZHh/+64XmPGick8DGoVdXy0VDh9JCZd/sb1dsc7ZupcuAWo2hpAgMBAAECggEAcbxsaNfPrK8N6ImEgFUvtG1B0Q/fMyRps5fKo4zxaWWu507OWJ2oGulxaZF6Q7/JN0A/8Dqw80ITF+O+6ei65uVA9ExSpUaqDY7Yez18H6EGqmZSHn1nj2u0jUuaLd8UiGagXcA0N1p/F5tzscKg0mlz+EmJM0hQWI78wrysYUFd50gDZUp8MkDQF1LoUaRuS5j7kvC2rcjGcG0d8DyrOhC1Y+hP135cP+lAuJt2aE2RqZo1gg3BkEG80ERZjthmlzmMAoYo7MD0oFhKqP7BeQRvK7y8SKr4PpsloIwkAXLzX+JFaoYh4tvRXyjV9OjC/KlsPuOOIGECAqCYTVkEiQKBgQDy9MrXdtZBPeV9b5HxIUUBcXrmjFWZLTbVqpldEZQc3LwaDCBz0mf5Zy4K3cF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pJGqp9EPsYsL8JEe9PXL1z80w7ILu+Bqja5NfxCX0Vsdf+1YhzqkaFpSxvKUXu+EZXV6G6J6339H2R4f/uuF5jxonJPAxqFXV8tFQ4fSQmXf7G9XbHO2bqXLgFqNoaQIDAQAB';



        $url = 'https://gateway.yundashoudan.com/api/shoudan/onlinePay';
        $price = 0.01;//Yii::$app->request->post('amount', false);
        $order_sn = 202307100831;//Yii::$app->request->post('order_sn', false);
        $openid = 'oZrVa5TElhooCUsF7R2tKkwDGV20';
        
        // 平台公钥：
        $publicKey = '044dfcc4b51f91e632b7c04e9b825691758a44d6cd0a8bf22041750f3dc0a09a4c25f788384c74d5fbf4e25703cc2e92366e82dc8e6cd0316ec72f98fe3ab30696';
        // 客户私钥
        $privateKey = '62e7cf548a28f1dac7314a7d35eea4221241258f647940e5e41638ca9f5f3206'; 
        $param = [
            "terminalNo"=>'51614460',
            "amount"=>$price,
            "orderNo"=>$order_sn,
            "payType"=>"ST",
            "transType"=>"00",
            "appId"=>"wxabdb9bdf0c0aae2b",
            "openId"=>$openid,
            "customer_id"=>53,
            "merchantNo"=>'897370272993006'
            // 商户号：897370272993006
            // 终端号：51614460
        ];
        $part = json_encode($param);

        $encrypt = $this->encrypt($part);
        echo $encrypt."<br/>";
        echo "加密后的长度：".strlen($encrypt)."<br/>";



        $decrypt = $this->decrypt($encrypt);
        echo $decrypt."<br/><br/>";




        $sign = $this->getSignGenerator($part);
        echo $sign."<br/>";
        echo "签名后的长度：".strlen($sign)."<br/>";


        $checkSign = $this->signCheck($part,$sign);
        echo "###".$checkSign."@@@"."<br/>";
        exit('ddd');



        //加密
        // require_once "Rsa.php";
        $rsa = new Rsa();
        // $data['name'] = 'Tom';
        // $data['age']  = '20';
        // $privEncrypt = $rsa->privEncrypt(json_encode($data));
        // echo '私钥加密后:'.$privEncrypt.'<br>';
         
        // $publicDecrypt = $rsa->publicDecrypt($privEncrypt);
        // echo '公钥解密后:'.$publicDecrypt.'<br>';
         
        $publicEncrypt = $rsa->pubEncrypt($part);
        echo '公钥加密后:'.$publicEncrypt.'<br>';
         

        echo "加密后的长度：".strlen($publicEncrypt);

        exit();
        // $privDecrypt = $rsa->privDecrypt($publicEncrypt);
        // echo '私钥解密后:'.$privDecrypt.'<br>';
        // $arr['bizContent'] = '046adcf1c1e8fea2fed9fc59c1d6ce3df962f0500e35579d13159378644c77789cc403dd5c925802b69ae6e7d0574ff621b400c6ea4b29b400f87e09503f5c45db45704efae4f9f6e25bd4aa46c8a9677c235df6518459b7dbb6343fa031b36c40f3d05f24ce52b2d760495f1968941f57d53cb9e731f283231b10fa4baab1ad866439c5b0ec78e1b9bbe9b517a17ed614b112de785c378a60a52302edb5f6537713d710e68146c0158164f9ff08b0539ca87a19f91b2a1bc9f5748b41ba44fdf652a3721e391c208c2e7418afc5f459eeb30ca3fd305eb80e0f6a8017d9412956aae6da93d10d184c08fb8b649cad91ae04643507405b0a207';

        
        // 签名
        $arr['sign'] = base64_encode(openssl_encrypt($part, 'AES-256-ECB', $privateKey, OPENSSL_RAW_DATA));
        //'3045022100df9a0f62fbe0c61a59ea08a4362548648021eb85ac581881adfa6e0202201dc4e0083f107a7fbcadeba9ad2783ca51ec5651cbb9e38c866caa';
        // var_dump($sign);
        // post请求
        $ret = $this->pddCurl($url,$arr,$token = '');
        halt($ret);

    }

    public function pddCurl($url,$data,$Token = null){
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
      if (!empty($data)){
          if(is_array($data) && $data){
             $json = json_encode($data,JSON_UNESCAPED_UNICODE);
          }
          curl_setopt($curl, CURLOPT_POST, 1);
          curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
          if($json){ //发送JSON数据
             curl_setopt($curl, CURLOPT_HEADER, 0);
             curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json; charset=utf-8',
                    'authorization:'.$Token,
                    'Content-Length: ' . strlen($json)
                 )
             );
          }
      }
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
      $res = curl_exec($curl);
      $errorno = curl_errno($curl);

      if ($errorno) {
        return array('errorno' => false, 'errmsg' => $errorno);
      }
      return json_decode($res, true);
    }


    public function post_curl($token,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'authorization:'.$token
            )
        );
        // curl_setopt($ch, CURLOPT_URL, YQPT_URL_ADD);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
    }


    public function curlPost($url,$data)
    {
        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        $params[CURLOPT_POST] = true;
        $params[CURLOPT_POSTFIELDS] = $data;
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接
        return $content;
    }

    // public function sign($privateKey, $content) {
    //     // 待签名内容转为字节数组
    //     $message = mb_convert_encoding($content, 'UTF-8');

    //     // 获取一条SM2曲线参数
    //     $sm2ECParameters = \phpseclib3\File\ASN1\Curves::getByName("sm2p256v1");
    //     // 构造domain参数
    //     $domainParameters = new \phpseclib3\Math\BigInteger($sm2ECParameters->getN());

    //     $privateKeyD = new \phpseclib3\Math\BigInteger($privateKey, 16);
    //     $privateKeyParameters = new \phpseclib3\Crypt\EC\PrivateKey($privateKeyD, $domainParameters);

    //     // 创建签名实例
    //     $sm2Signer = new \phpseclib3\Crypt\EC\SM2();

    //     // 初始化签名实例，带上ID，默认值为: 1234567812345678
    //     $sm2Signer->init(true, new \phpseclib3\Crypt\Common\ParametersWithID(new \phpseclib3\Crypt\Common\ParametersWithRandom($privateKeyParameters, new \phpseclib3\Crypt\Common\Random("SHA1PRNG")), "1234567812345678"));
    //     $sm2Signer->update($message);
    //     // 生成签名，签名分为两部分r和s，分别对应数组中的索引0和1
    //     $signBytes = $sm2Signer->sign();

    //     return $signBytes;
    // }

    public function sign($privateKey, $content) {
        // 待签名内容转为字节数组
        $message = mb_convert_encoding($content, 'UTF-8');

        // 获取一条SM2曲线参数
        $sm2ECParameters = \phpseclib3\File\ASN1\Curves::getByName("sm2p256v1");
        // 构造domain参数
        $domainParameters = new \phpseclib3\Math\BigInteger($sm2ECParameters->getN());

        $privateKeyD = new \phpseclib3\Math\BigInteger($privateKey, 16);
        $privateKeyParameters = new \phpseclib3\Crypt\EC\PrivateKey($privateKeyD, $domainParameters);

        // 创建签名实例
        $sm2Signer = new \phpseclib3\Crypt\EC\SM2();

        // 初始化签名实例，带上ID，默认值为: 1234567812345678
        $sm2Signer->init(true, new \phpseclib3\Crypt\Common\ParametersWithID(new \phpseclib3\Crypt\Common\ParametersWithRandom($privateKeyParameters, new \phpseclib3\Crypt\Common\Random("SHA1PRNG")), "1234567812345678"));
        $sm2Signer->update($message);
        // 生成签名，签名分为两部分r和s，分别对应数组中的索引0和1
        $signBytes = $sm2Signer->sign();

        return \phpseclib3\Math\BigInteger::encode($signBytes, 16);
    }





}


/**
 * RSA签名类
 */
class Rsa
{
    public $publicKey = '/cert/publicKey.pem';
    public $privateKey = '/cert/privateKey.pem';
    private $_privKey;

    /**
     * * private key
     */
    private $_pubKey;

    /**
     * * public key
     */
    private $_keyPath;

    /**
     * * the keys saving path
     */

    /**
     * * the construtor,the param $path is the keys saving path
     * @param string $publicKey  公钥
     * @param string $privateKey 私钥
     */
    public function __construct($publicKey = null, $privateKey = null)
    {
        $this->setKey($publicKey, $privateKey);
    }

    /**
     * 设置公钥和私钥
     * @param string $publicKey  公钥
     * @param string $privateKey 私钥
     */
    public function setKey($publicKey = null, $privateKey = null)
    {
        if (!is_null($publicKey)) {
            $this->publicKey = $publicKey;
        }
        if (!is_null($privateKey)) {
            $this->privateKey = $privateKey;
        }
    }

    /**
     * * setup the private key
     */
    private function setupPrivKey()
    {
        if (is_resource($this->_privKey)) {
            return true;
        }
        $pem = chunk_split($this->privateKey, 64, "\n");
        $pem = "-----BEGIN PRIVATE KEY-----\n" . $pem . "-----END PRIVATE KEY-----\n";
        $this->_privKey = openssl_pkey_get_private($pem);
        return true;
    }

    /**
     * * setup the public key
     */
    private function setupPubKey()
    {
        if (is_resource($this->_pubKey)) {
            return true;
        }
        $pem = chunk_split($this->publicKey, 64, "\n");
        $pem = "-----BEGIN PUBLIC KEY-----\n" . $pem . "-----END PUBLIC KEY-----\n";
        $this->_pubKey = openssl_pkey_get_public($pem);
        return true;
    }

    /**
     * * encrypt with the private key
     */
    public function privEncrypt($data)
    {
        if (!is_string($data)) {
            return null;
        }
        $this->setupPrivKey();
        $r = openssl_private_encrypt($data, $encrypted, $this->_privKey);
        if ($r) {
            return base64_encode($encrypted);
        }
        return null;
    }

    /**
     * * decrypt with the private key
     */
    public function privDecrypt($encrypted)
    {
        if (!is_string($encrypted)) {
            return null;
        }
        $this->setupPrivKey();
        $encrypted = base64_decode($encrypted);
        $r = openssl_private_decrypt($encrypted, $decrypted, $this->_privKey);
        if ($r) {
            return $decrypted;
        }
        return null;
    }

    /**
     * * encrypt with public key
     */
    public function pubEncrypt($data)
    {
        if (!is_string($data)) {
            return null;
        }
        $this->setupPubKey();
        $r = openssl_public_encrypt($data, $encrypted, $this->_pubKey);
        if ($r) {
            return base64_encode($encrypted);
        }
        return null;
    }

    /**
     * * decrypt with the public key
     */
    public function pubDecrypt($crypted)
    {
        if (!is_string($crypted)) {
            return null;
        }
        $this->setupPubKey();
        $crypted = base64_decode($crypted);
        $r = openssl_public_decrypt($crypted, $decrypted, $this->_pubKey);
        if ($r) {
            return $decrypted;
        }
        return null;
    }

    /**
     * 构造签名
     * @param string $dataString 被签名数据
     * @return string
     */
    public function sign($dataString)
    {
        $this->setupPrivKey();
        $signature = false;
        openssl_sign($dataString, $signature, $this->_privKey);
        return base64_encode($signature);
    }

    /**
     * 验证签名
     * @param string $dataString 被签名数据
     * @param string $signString 已经签名的字符串
     * @return number 1签名正确 0签名错误
     */
    public function verify($dataString, $signString)
    {
        $this->setupPubKey();
        $signature = base64_decode($signString);
        $flg = openssl_verify($dataString, $signature, $this->_pubKey);
        return $flg;
    }

    public function __destruct()
    {
        is_resource($this->_privKey) && @openssl_free_key($this->_privKey);
        is_resource($this->_pubKey) && @openssl_free_key($this->_pubKey);
    }
}